package com.atguigu.gulimall.ware.listener;
import com.atguigu.common.to.mq.OrderTo;
import com.atguigu.common.to.mq.StockLockedTo;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.io.IOException;

/**
 * @Classname StockReleaseListener
 * @Description 监听库存解锁
 * @Date 2021/10/20 10:25
 * @Author Anonymous
 */
@SuppressWarnings("all")
@Slf4j
@RabbitListener(queues = "stock.release.stock.queue")
@Service
public class StockReleaseListener {


    @Resource
    private WareSkuService wareSkuService;

    /**
     * 库存自动解锁：两个场景，先考虑第2个
     * 1、下订单成功，库存锁定成功，但是接下来的业务调用失败，导致订单回滚，之前锁定的库存就要自动解锁
     * 2、假如订单失败本身就是因为锁定库存失败导致的，也就是如果锁定两个商品的库存，第一个成功，而第二个失败的场景
     * <p>
     * 只要解锁库存的消息失败，一定要告诉服务器此次解锁是失败的如何告诉，就是启动手动ack机制
     */
    @RabbitHandler
    public void handleStockLockedRelease(StockLockedTo to, Message message, Channel channel) throws IOException {

        log.info("************收到库存解锁的消息****************");
        try {
            wareSkuService.unlockStock(to);
            // 执行成功的 回复 [仅回复自己的消息]
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }

    @RabbitHandler
    public void handleOrderCloseRelease(OrderTo orderTo, Message message, Channel channel) throws IOException {
        log.info("************从订单模块收到库存解锁的消息********************");
        try {
            wareSkuService.unlockStock(orderTo);
            // 执行成功的 回复 [仅回复自己的消息]
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }
}
